package middleware

import (
	"blog2021/model"
	"time"

	"github.com/gin-gonic/gin"
)

func AccessLog() gin.HandlerFunc {
	var accessLogChan = make(chan model.AccessLog, 100)
	go func() {
		for v := range accessLogChan {
			model.AddAccessLog(&v)
		}
	}()
	return func(c *gin.Context) {
		startTime := time.Now()
		c.Next()
		endTime := time.Now()

		accessLog := model.AccessLog{
			StatusCode:  c.Writer.Status(),
			LatencyTime: int(endTime.Sub(startTime).Milliseconds()),
			Address:     c.Request.Host,
			Method:      c.Request.Method,
			Path:        c.Request.RequestURI,
		}

		accessLogChan <- accessLog
	}
}
